package com.rongkang.interview.juc.blockingqueue;

/**
 * @Description:
 * @author: 荣康
 * @date: 2021/12/11
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线操作资源类
 * 判断 干活 通知
 * 防止虚假唤醒机制
 * 场景： 对空调进行加1度，对空调进行减1度
 */
class ShareData {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increment() {
        lock.lock();
        try {
            //判断
            while (number != 0) {
                //等待不能生产
                condition.await();
            }
            //干活
            number++;
            System.out.println(Thread.currentThread().getName() + "\t " + number);
            //通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void decrement() {
        lock.lock();
        try {
            while (number == 0) {
                //等待不能消费
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "\t " + number);
            //唤醒所有等待的线程
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class ProdConsumerTraditionDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                shareData.increment();
            }
        }, "t1").start();
        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                shareData.decrement();
            }
        }, "t2").start();

    }
}
